package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.domain.Hr;
import com.ruoyi.system.domain.Mylogin;
import com.ruoyi.system.domain.Seeker;
import com.ruoyi.system.service.IHrService;
import com.ruoyi.system.service.IMyloginService;
import com.ruoyi.system.service.ISeekerService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *移植SysLoginService
 */
@Component
public class MyLoginService {
    @Autowired
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private IHrService hrService;
    @Autowired
    private ISeekerService seekerService;
    @Autowired
    private IMyloginService myloginService;
    @Autowired
    private MyTokenService myTokenService;
    /**
     *登录验证
     * @param userphone 登录电话
     * @param userrole 用户角色
     * @param password

     * @return 结果
     */
    public String login(String userphone,String userrole, String password) {

        // 登录前置校验
        Long userid = loginPreCheck(userphone, userrole, password);
        System.out.println("userid="+userid);
        if (userid == -1) {
            return "请进行注册";
        } else if (userid == -2) {
            return "密码错误";
        } else if(userid==-3){
            return "登录出现了非HR和seeker用户";
        }
        else {
            // 用户验证
           /* Authentication authentication = null;
            try {
                //生成普通的token改写这里了
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userphone, password);
                AuthenticationContextHolder.setContext(authenticationToken);
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                //authentication = authenticationManager.authenticate(authenticationToken);
            } finally {
                AuthenticationContextHolder.clearContext();
            }*/
            //生成token成功就插入日志了
            Mylogin mylogin=new Mylogin();
            // AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
           // LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            //设置日志内容
            final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            final String ip = IpUtils.getIpAddr();
            String address = AddressUtils.getRealAddressByIP(ip);
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();

            mylogin.setUserRole(userrole);
            mylogin.setUserId(userid);
            mylogin.setIpaddr(ip);
            mylogin.setLoginLocation(address);
            mylogin.setMsg("登录成功");
            mylogin.setBrowser(browser);
            mylogin.setOs(os);
            mylogin.setStatus(Constants.SUCCESS);
            mylogin.setLoginTime(new Date());

            //插入数据
            SpringUtils.getBean(IMyloginService.class).insertMylogin(mylogin);
            String token = myTokenService.mylogincreatedToken(mylogin.getUserRole(),mylogin.getUserId());
            return token;
        }

    }
    /**
     * 登录前置校验
     * @param userrole
     * @param userphone

     * @param password
     */
    private Long loginPreCheck(String userphone,String userrole, String password) {
        if(userrole.equals("hrlogin")){
            return checkloginhr(userphone,password);

        }
        else if(userrole.equals("employeelogin")){
            return checkloginseeker(userphone,password);

        }
        else return (long) -3;
    }
    /**-1没注册,userid成功,-2密码错误
     * 检查登录HR信息
     * @param phone
     * @param pwd

     * @return
     */
    private Long checkloginhr(String phone,String pwd){
        Hr hr = hrService.selectHrByHrphone(phone);
        if(hr==null){

            return (long) -1;
        }
        else {
            if(hr.getHrPwd().equals(pwd)){
                return hr.getHrId();
            }
            else return (long) -2;
        }

    }
    /** -1没注册,userid成功,-2密码错误
     * 检查登录的求职者信息
     * @param pwd
     * @param phone
     * @return
     */
    private Long checkloginseeker(String phone,String pwd){
        Seeker seeker = seekerService.selectSeekerBySeekerTel(phone);
        if(seeker==null){
            return  (long) -1;
        }
        else{
            if(seeker.getSeekerPwd().equals(pwd)){
                return seeker.getSeekerId();
            }
            else{
                return (long) -2;
            }
        }
    }
    //返回登录用户结果
    public AjaxResult getroleandid(HttpServletRequest request, HttpServletResponse response){
        String token = request.getParameter("token");
        if(token.equals("notoken")){
            System.out.println("没有登录");
            return new AjaxResult(1,"请先进行登录");
        }
        else {
            System.out.println("有登录用户"+token);
            String loginrule = myTokenService.getloginrole(token);
            Long ruleid = myTokenService.getloginid(token);
            return new AjaxResult(200,loginrule,ruleid);
        }

    }
    //返回登录用户名字
    public AjaxResult getrolename(HttpServletRequest request, HttpServletResponse response){
        String token = request.getParameter("token");
        if(token.equals("notoken")){
            System.out.println("没有登录");
            return new AjaxResult(1,"请先进行登录","notoken");
        }
        else {
            System.out.println("有登录用户"+token);
            String loginrule = myTokenService.getloginrole(token);
            Long ruleid = myTokenService.getloginid(token);
            if(loginrule.equals("employeelogin")){
                return new AjaxResult(200,seekerService.selectSeekerBySeekerId(ruleid).getSeekerName(),"seekerlogin");
            }
            else if(loginrule.equals("hrlogin")){}
            return new AjaxResult(200,hrService.selectHrByHrId(ruleid).getHrName(),"hrlogin");
        }
    }
    //根据登录信息确定当前登录用户是表中的哪个

}
